package cameragps;

import java.util.Date;

import net.rim.device.api.i18n.SimpleDateFormat;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.XYEdges;
import net.rim.device.api.ui.component.AutoTextEditField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.PopupScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.BorderFactory;

/**
 * This screen is used to notify user the location and enter decription of image
 * to upload it to server
 * 
 * 
 */
public final class ImageScreen extends PopupScreen {

	public static String EXTENSION = ".jpg";

	private static byte[] rawImage;

	private ImageScreen m_imageScreen;

	AutoTextEditField m_myWord;

	protected double m_Logitude;
	protected double m_Latitude;
	protected String m_locationAddress;

	boolean sent;

	VerticalFieldManager locationTextManager;
	HorizontalFieldManager latLongFieldManager;

	LabelField latLabelField;
	LabelField longLabelField;
	LabelField placeLabelField;

	public ImageScreen(final byte[] raw, double Logitude, double Latitude,
			String locationAddress) {
		super(new VerticalFieldManager(Manager.VERTICAL_SCROLL));
		if (raw == null)
			return;

		m_Logitude = Logitude;
		m_Latitude = Latitude;
		m_locationAddress = locationAddress;

		m_imageScreen = this;

		rawImage = raw;

		HorizontalFieldManager locationFieldManager = new HorizontalFieldManager();

		locationTextManager = new VerticalFieldManager();
		locationTextManager.add(new LabelField("Location:"));

		placeLabelField = new LabelField(m_locationAddress);
		locationTextManager.add(placeLabelField);

		locationFieldManager.add(locationTextManager);

		VerticalFieldManager refreshFieldManager = new VerticalFieldManager(
				USE_ALL_WIDTH);
		ButtonField refreshButtonField = new ButtonField("Refresh", FIELD_RIGHT);

		refreshButtonField.setChangeListener(new FieldChangeListener() {

			public void fieldChanged(Field field, int context) {
				ThreadUtils.showScreenAndWait(new Runnable() {
					public void run() {
						final boolean result = LocationTracker.getSinglePoint();

						if (result) {
							m_Logitude = LocationTracker.m_Logitude;
							m_Latitude = LocationTracker.m_Latitude;
							m_locationAddress = LocationTracker.m_locationAddress;

							UiApplication.getUiApplication().invokeLater(
									new Runnable() {

										public void run() {
											latLabelField.setText("Lat: "
													+ m_Latitude);
											longLabelField.setText("Long: "
													+ m_Logitude);
											placeLabelField
													.setText(m_locationAddress);

										}
									});
						}

					}
				}, "Updating location");
			}
		});

		refreshFieldManager.add(refreshButtonField);

		locationFieldManager.add(refreshFieldManager);

		// creating latitude longitude field

		latLongFieldManager = new HorizontalFieldManager(USE_ALL_WIDTH);

		latLabelField = new LabelField("Lat: " + m_Latitude);
		latLongFieldManager.add(latLabelField);

		VerticalFieldManager longFieldManager = new VerticalFieldManager(
				USE_ALL_WIDTH);
		longLabelField = new LabelField("Long: " + m_Logitude, FIELD_RIGHT);
		longFieldManager.add(longLabelField);

		latLongFieldManager.add(longFieldManager);

		// creating description field

		VerticalFieldManager descriptionFieldManager = new VerticalFieldManager(
				Field.FIELD_HCENTER);

		LabelField lab_Word = new LabelField("Enter Photo Description");
		m_myWord = new AutoTextEditField() {
			protected synchronized void paint(Graphics aGraphics) {
				aGraphics.setColor(Color.BLACK);
				super.paint(aGraphics);
			};
		};
		m_myWord.setBorder(BorderFactory.createBitmapBorder(new XYEdges(14, 14,
				14, 14), Bitmap.getBitmapResource("bg.png")));

		descriptionFieldManager.add(lab_Word);
		descriptionFieldManager.add(m_myWord);

		// Creating Buttons

		HorizontalFieldManager actionFieldManager = new HorizontalFieldManager(
				Field.FIELD_HCENTER);

		ButtonField photoButton = new ButtonField("Send");
		photoButton.setChangeListener(new SendListener(raw));
		actionFieldManager.add(photoButton);

		ButtonField cancelButton = new ButtonField("Cancel");
		cancelButton.setChangeListener(new CancelListener());
		actionFieldManager.add(cancelButton);

		this.add(locationFieldManager);
		this.add(latLongFieldManager);
		this.add(descriptionFieldManager);
		this.add(actionFieldManager);
	}

	protected boolean invokeAction(int action) {
		boolean handled = super.invokeAction(action);
		if (!handled) {
			switch (action) {
			case ACTION_INVOKE: {
				return true;
			}
			}
		}
		return handled;
	}

	private class SendListener implements FieldChangeListener {
		private byte[] m_raw;

		String xmlMessage;

		SendListener(byte[] raw) {
			m_raw = raw;
		}

		public void fieldChanged(Field field, int context) {

			// String defaultEmailAddress = Session.waitForDefaultSession()
			// .getServiceConfiguration().getEmailAddress() ;

			// String defaultEmailAddress = "rafale@thetigerparty.com";

			final String FILE_NAME = helloBerry.dID
					+ new SimpleDateFormat("MMddyymmss").format(new Date())
					+ EXTENSION;

			xmlMessage = ImageUtils.xmlBuilder(
					new String[] { FILE_NAME, m_myWord.getText(),
							String.valueOf(m_Latitude),
							String.valueOf(m_Logitude), m_locationAddress },
					m_raw);

			final PopupScreen waitScreen = ThreadUtils
					.getWaitPopUp("Please Wait...");

			ThreadUtils.runningSequance(new Runnable() {

				public void run() {
					UiApplication.getUiApplication().pushScreen(waitScreen);
				}
			}, new Runnable() {

				public void run() {
					sent = ImageUtils.SendHttpPost(xmlMessage);
				}
			}, new Runnable() {

				public void run() {
					UiApplication.getUiApplication().popScreen(waitScreen);

					if (sent) {

						ImageUtils.saveNew(FILE_NAME, m_myWord.getText(),
								String.valueOf(m_Latitude),
								String.valueOf(m_Logitude), m_locationAddress,
								true, rawImage);
						Dialog.alert("Your photo has been sent/saved!");
					} else {

						int reply = Dialog
								.ask(Dialog.D_OK_CANCEL,
										"Sorry you could not connect to the internet Press ok to send your photo later from the Outbox");

						if (reply == Dialog.OK) {
							ImageUtils.saveNew(FILE_NAME, m_myWord.getText(),
									String.valueOf(m_Latitude),
									String.valueOf(m_Logitude),
									m_locationAddress, false, rawImage);
						}
					}

				}
			});

			UiApplication.getUiApplication().popScreen(m_imageScreen);
		}
	}

	private class CancelListener implements FieldChangeListener {
		public void fieldChanged(Field field, int context) {
			close();
		}
	}

	protected boolean keyChar(char c, int status, int time) {
		if (c == Characters.ESCAPE)
			close();
		return super.keyChar(c, status, time);
	}

}